/* Create a SessionFactory based on the hibernate.cfg.xml file. From a
SessionFactory, you can create an individual Session*/
SessionFactory sessionfactory = new
Configuration().configure().buildSessionFactory();
session =
sessionfactory.openSession();
System.out.println("Inserting Record");
//Creating Book Object
Book book = new
Book();
//Begin a transaction within the
session
Transaction tx = session.beginTransaction();
book.setTitle("Green Eggs and
Ham");
book.setPrice(5.99);
//save the book object into the
database
session.save(book);
//the change in memory would not propagate to //database unless a transaction
is committed or //rollback.
tx.commit();
// Perform a
query
List books =
session.createQuery("from Book").list();
if (books.isEmpty() != true) {
System.out.println ("First Book Exists
- its title is:");
Book firstbook =
(Book)books.get(0);
System.out.println
(firstbook.getTitle());
} else {
System.out.println ("List is Empty");
}
session.close();
System.out.println("Done");
}
catch(Exception e) {
System.out.println(e.getMessage());
}